<template>
  <el-drawer
      size="50%"
      title="AB测试"
      direction="rtl"
      :model-value="true"
      :before-close="handleCancel"
  >
    <div class="form-wrapper">
      <el-form class="custom-form" ref="form" :rules="rules" :model="form" label-width="80px" label-position="top" :disabled="readOnly">
        <el-form-item label="组件名称" prop="name">
          <el-input class="custom-input custom-input-name"
                    v-model.trim="form.name"
                    type="text"
                    maxlength="15"
                    :show-word-limit="true">
          </el-input>
        </el-form-item>

        <div class="dialog-tip">用户将按照流量分配比例随机进入任一分支，流量总和为100%</div>

        <el-row style="margin-bottom: 18px">
          <div class="group" v-for="(item, index) in form.weights" :key="index">
            <div class="group-name">
              实验组 {{ index+1}}
            </div>
            <div class="group-value">
              <div class="value-label">
               流量分配
              </div>
              <el-input type="number" v-model="item.weighted"></el-input>
              <div class="value-decorator">%</div>
            </div>
            <el-button link type="danger" @click="deleteWeight(index)">删除</el-button>
          </div>
        </el-row>

        <div class="add-group">
          <el-button @click="addWeights" :disabled="form.weights.length === 10">添加实验组</el-button>
          <div>剩余流量：{{leftFlow}}%</div>
        </div>

      </el-form>
      <div class="form-footer">
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确定</el-button>
      </div>
    </div>
  </el-drawer>
</template>

<script>
import { nanoid } from "nanoid";
import {NodeDrawerDataModel} from "@/views/workTable/dataModel/NodeDrawerDataModel";

export default {
  props: {
    dialogData: {
      type: Object,
      default() {
        return {}
      },
    },
    addNodeEventData: {
      type: Object,
      default() {
        return {}
      }
    },
    readOnly: Boolean,
  },
  emits: ['confirm', 'cancel'],

  data() {
    return {
      form: {
        name: '',
        weights: [],
      },
      rules: {
        name: [
          {
            required: true,
            message: '请输入组建名称'
          }
        ]
      },

      maxFlow: 100,
      minFLow: 0,
      maxWeight: 10,
    }
  },

  computed: {
    leftFlow() {
      const currentFlow = this.form.weights.reduce((total, current) => total += Number(current.weighted) || 0, 0)
      return this.maxFlow - currentFlow
    }
  },

  mounted() {
    if (this.dialogData && Object.keys(this.dialogData).length) {
      this.form = this.dialogData
    }

    if (Object.keys(this.addNodeEventData).length && this.addNodeEventData.graph && this.addNodeEventData.cell) {
      const {graph, cell} = this.addNodeEventData
      const edges = graph.getOutgoingEdges(cell) ?? []

      // this.form.weights = edges && edges.map(edgeModel => ({
      //   weighted: edgeModel.getData().dialogData.weighted
      // })) || []

      // TODO 检查ID 绑定ID
      this.form.weights = edges && edges.map(edgeModel => ({
        ...edgeModel.getData().dialogData
      })) || []

      console.log('mounted abtest form', this.form)
    }
  },

  methods: {
    getWeightItem(index) {
      return {
        id: nanoid(),
        weighted: 0,
        weightIndex: index
      }
    },

    addWeights() {
      if (this.form.weights.length === this.maxWeight) {
        this.$message.warning(`实验组不能超过${this.maxWeight}个，请重新设置`)
        return
      }
      this.form.weights.push(this.getWeightItem(this.form.weights.length))
    },

    deleteWeight(index) {
      this.form.weights.splice(index, 1)
    },

    handleCancel() {
      this.$emit('cancel')
    },

    handleConfirm() {
      if (!this.form.name) {
        this.$message.warning('请填写组建名称')
        return
      }

      if (this.leftFlow > 0) {
        this.$message.warning("还有剩余流量未分配，请重新分配")
        return
      }

      if (this.leftFlow < 0) {
        this.$message.warning("剩余流量不足")
        return
      }

      const zeroWeight = this.form.weights.filter(item => Number(item.weighted) === 0)
      if (zeroWeight.length) {
        this.$message.warning("实验组的流量分配不能为0")
        return
      }

      this.$emit("confirm", new NodeDrawerDataModel({
        dialogData: this.form,
      }))
      this.handleCancel()
    },
  }
}
</script>

<style scoped lang="scss">
.form-wrapper {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  font-size: 14px;
}

.custom-input-name {
  //width: 440px;
}

.custom-input-anchor-input {
  width: 104px;
}

.custom-form {
  flex: 1;
}

.form-footer {
  display: flex;
  justify-content: flex-end;
}

.dialog-tip {
  //width: 440px;
  font-size: 14px;
  color: #666;
  background: #F0F2FF;
  padding: 12px 16px;
  margin-bottom: 18px;
}

.add-group {
  //width: 440px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.group {
  display: flex;
  align-items: center;
  word-break: keep-all;
  justify-content: space-between;
  width: 380px;
  margin-bottom: 18px;

  .group-value {
    display: flex;
    align-items: center;

    .value-label {
      margin-right: 5px;
    }

    .value-decorator {
      margin-left: 5px;
    }
  }
}
</style>
